﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hotnet.Dal.BaseRepository;
using Hotnet.Entity;
using LinqExt;
using Hotnet.Entity.Search;

namespace Hotnet.Dal.NSDalPicture
{
	public class DalPictureList : Repository<PictureList>
	{
		public ViewPictureList[] List(SearchPictureList condition, int pageNo, int pageSize, out int totalCount)
		{
			int from = pageNo * pageSize + 1;
			int to = (pageNo + 1) * pageSize;
			totalCount = 0;

			string listTypeCondition = "";
			string orderByCondition = "";
			string groupNameCondition = "";
			string isPublishedCondition = "";
			string pictureCategoryCondition = "";

			if(condition.ListType!=null)
				listTypeCondition = string.Format(" and ListType={0} ",(int)condition.ListType);
			if (condition.OrderType == Hotnet.Entity.Enum.EnumOrder.添加时间||condition.OrderType==null)
				orderByCondition = " PictureList.IsPublished,PictureList.AddTime ";
			else
				orderByCondition = " PictureList.IsPublished,ClickCount ";
			if(!string.IsNullOrEmpty(condition.PictureGroupName))
				groupNameCondition = string.Format(" and Name like '%{0}%'",condition.PictureGroupName);
			if (condition.PictureCategroyId != null)
				pictureCategoryCondition = string.Format(" and CategoryID={0}", condition.PictureCategroyId);
			if (condition.IsPublished != null)
				isPublishedCondition = string.Format(" and PictureList.IsPublished={0} ",(int)condition.IsPublished);

			string strSql = string.Format(@"select * from (SELECT ROW_NUMBER() OVER (ORDER BY {5} desc)AS Row
										,PictureGroup.[GroupID]
										,[CoverImageID]
										,[SourceFromID]
										,[Name]
										,[Description]
										,[CategoryID]
										,[OrderInCategory]
										,[ClickCount]
										,PictureList.[AddTime]
										,[DefineType]
										,PictureList.[IsPublished]
										,[ListType]
										,[CoverImageSrc]
										FROM [PictureGroup] join PictureList on PictureGroup.GroupID=PictureList.GroupID where 1=1 {0} {1} {2} {6} {7}) t1 WHERE Row between {3} and {4}", listTypeCondition, groupNameCondition, isPublishedCondition, from, to, orderByCondition,pictureCategoryCondition,isPublishedCondition);
			string strCount = string.Format(@"SELECT count(*) 
										FROM [PictureGroup] join PictureList on PictureGroup.GroupID=PictureList.GroupID where 1=1 {0} {1} {2} {3} {4}", listTypeCondition, groupNameCondition, isPublishedCondition,pictureCategoryCondition,isPublishedCondition);
			totalCount = disableCacheDataContext.ExecuteQuery<int>(strCount).FirstOrDefault();
			return disableCacheDataContext.ExecuteQuery<ViewPictureList>(strSql).ToArray();
		}
	}
}

